<?php
include_once 'application/application.php';


class Page_install {

    private $obj_types = array();
    private $btypes = array();
    private $apps = array();
    private $oss = array();
    private $db_types = array();


    public $action;
    public $error;


    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->printOut(DB::getError());
        }

        $this->obj_types = getObjTypes();
        $this->oss = getClientOSs();
        $this->db_types = getClientDbTypes();
        $this->btypes = getBuildTypes();
        $this->apps = getClientApps();



    }

    public function __destruct() {

    }








    public function Form($params=array()) {
        if (Arr::getValue($params, 'error', false))     $params['error']   = '<div class="control-group"><span class="label label-important"> Ошибка </span> '.$params['error'].'</div>';
        if (Arr::getValue($params, 'message', false))   $params['message'] = '<div class="control-group"><span class="label label-info"> Информация </span> '.$params['message'].'</div>';

        $params['obj_types'] = $this->obj_types;
        $params['obj_types'][0] = array('id'=>0,'name'=>'Выберите тип объекта');

        $params['db_types'] = $this->db_types;
        $params['db_types'][0] = array('id'=>0,'name'=>'Выберите тип БД');

        $params['apps'] = $this->apps;
        $params['apps'][0] = array('id'=>0,'name'=>'Выберите программу');

        $params['oss'] = $this->oss;
        $params['oss'][0] = array('id'=>0,'name'=>'Выберите OS');

        $params['btypes'] = $this->btypes;
        $params['btypes'][0] = array('id'=>0,'name'=>'Выберите тип помещения');

        $params['datatypes'] = getDataTypes();
        $params['datatypes'][0] = array('id'=>0,'name'=>'Выберите тип данных');



        $params['action'] = $this->action;

        switch ($this->action) {
            case ACTIONS::INSTALL_NEWDS : $params['legend'] = 'Создание нового подключения'; break;
            default: $params['legend'] = 'Параметры подключения';
        }

        $content = '';
        $content .= includeFile(APP_PAGE_PARTS.'forms/form_ds.php', $params);


        $this->printOut( $content );

    }



    /**
     * Проверка полей
     * @param type $params
     */
    public function checkFields($params) {
        $wrongFields = array();


        $name = 'tbl';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if (!$msg && !(strtolower(substr($var, 0, 4))=='obj_')) $msg = 'Имя таблицы должно иметь вид obj_№№№';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'name';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'description';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'address';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'placed';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'photo';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'obj_type';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !($var>0 && array_key_exists($var, $this->obj_types))) $msg = 'Недопустимое значение';
        if ($msg) $wrongFields[$name] = $msg;



        $name = 'db_type';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !($var>0 && $var<=count($this->db_types))) $msg = 'Недопустимое значение';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'db_path';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'db_descr';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'app';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !($var>0 && $var<=count($this->apps))) $msg = 'Недопустимое значение';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'os';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !($var>0 && $var<=count($this->oss))) $msg = 'Недопустимое значение';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'os_descr';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'remote';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;



        $name = 'created';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        else {
            $date = DateTime::createFromFormat('Y-m-d', $var);
            if (!$msg && !$date) $msg = 'Недопустимое значение';
            else {
                if (Arr::getValue($params, 'action', '-') == ACTIONS::INSTALL_NEWDS) {
                    $now = time();
                    $val = $date->getTimestamp();
                    $diff = $now-$val;
                    if (($diff<0) || $diff>(60*60*24*7*2)) $msg = 'Недопустимая дата';//не более 2 недели
                }
            }
        }
        if ($msg) $wrongFields[$name] = $msg;

        return $wrongFields;

    }




    public function saveFormData() {
        //$table='', $description='', $obj_type=0, $app=0, $os=0



        $J = new JSON();
        $params = array(
            'action'            => mysql_escape_string($J->readVar('action')),
            'id'                => (int)$J->readVar('id', 0),
            'tbl'               => mysql_escape_string(strtolower($J->readVar('tbl'))),
            'sen'               => mysql_escape_string(strtolower($J->readVar('sen'))),
            'name'              => mysql_escape_string($J->readVar('name', '')),
            'description'       => mysql_escape_string($J->readVar('description', '')),
            'address'           => mysql_escape_string($J->readVar('address', '')),
            'placed'            => mysql_escape_string($J->readVar('placed', '')),
            'photo'             => mysql_escape_string($J->readVar('photo', '')),
            'obj_type'          => (int)$J->readVar('obj_type', 0),
            'build_type'        => (int)$J->readVar('build_type', 0),
            'db_type'           => (int)$J->readVar('db_type', 0),
            'db_path'           => mysql_escape_string($J->readVar('db_path', '')),
            'db_descr'          => mysql_escape_string($J->readVar('db_descr', '')),
            'app'               => (int)$J->readVar('app', 0),
            'os'                => (int)$J->readVar('os', 0),
            'os_descr'          => mysql_escape_string($J->readVar('os_descr', '')),
            'remote'            => mysql_escape_string($J->readVar('remote', '')),
            'created'           => mysql_escape_string($J->readVar('created', ''))
        );

        $wrongFields = $this->checkFields($params);






        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }




        /*
         * Отключение этого куска кода = продажа души дьяволу:
         *     В одной ьаблице мы пытаемся хранить отображения и источники данных, что бред.
         *
        $res = DB::query("SELECT id FROM `admin_conn_history` WHERE tbl = '{$params['tbl']}' AND id <> {$params['id']}");
        if (!$res || !DB::state()) {
            $J->error('Ошибка при работе с базой данных');
            return $J;
        }
        if ($res->num_rows) {
            $J->wrongFields = array('tbl' => 'Такая таблица уже существует');
            return $J;
        }
        */

        $q = "INSERT INTO `admin_conn_history`
                           (`id`, `name`,              `tbl`,               `sen`,              `description`,              `address`,              `placed`,              `photo`,
                                    `obj_type`,              `build_type`,            `db_type`,              `db_path`,              `db_descr`,
                                    `app`,              `os`,              `os_descr`,              `remote`,              `created`)
                    VALUES (NULL, '{$params['name']}', '{$params['tbl']}',  '{$params['sen']}', '{$params['description']}', '{$params['address']}', '{$params['placed']}', '{$params['photo']}',
                                    '{$params['obj_type']}', '{$params['build_type']}', '{$params['db_type']}', '{$params['db_path']}', '{$params['db_descr']}',
                                    '{$params['app']}', '{$params['os']}', '{$params['os_descr']}', '{$params['remote']}', '{$params['created']}' )";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных ('.DB::$mysqli->error.')');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_DS, $params);

        $J->reLocate($_SERVER['PHP_SELF'].'?download='.$J->insertedId);
        return $J;
        //$this->selectDataSourceForm($id);

    }



    public function updateFormData() {
        $J = new JSON();
        $params = array(
            'action'            => mysql_escape_string($J->readVar('action')),
            'id'                => (int)$J->readVar('id', 0),
            'tbl'               => mysql_escape_string(strtolower($J->readVar('tbl'))),
            'sen'               => mysql_escape_string(strtolower($J->readVar('sen'))),
            'name'              => mysql_escape_string($J->readVar('name', '')),
            'description'       => mysql_escape_string($J->readVar('description', '')),
            'address'           => mysql_escape_string($J->readVar('address', '')),
            'placed'            => mysql_escape_string($J->readVar('placed', '')),
            'photo'             => mysql_escape_string($J->readVar('photo', '')),
            'obj_type'          => (int)$J->readVar('obj_type', 0),
            'build_type'        => (int)$J->readVar('build_type', 0),
            'db_type'           => (int)$J->readVar('db_type', 0),
            'db_path'           => mysql_escape_string($J->readVar('db_path', '')),
            'db_descr'          => mysql_escape_string($J->readVar('db_descr', '')),
            'app'               => (int)$J->readVar('app', 0),
            'os'                => (int)$J->readVar('os', 0),
            'os_descr'          => mysql_escape_string($J->readVar('os_descr', '')),
            'remote'            => mysql_escape_string($J->readVar('remote', '')),
            'created'           => mysql_escape_string($J->readVar('created', ''))
        );

        $wrongFields = $this->checkFields($params);



        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }


        $q = "SELECT * FROM `admin_conn_history` WHERE id = {$params['id']}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при работе с базой данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        if (!($oldvalue = mysqli_fetch_array($res, MYSQLI_ASSOC))) {
            $J->error('Исходные данные не найдены <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $q = "UPDATE `admin_conn_history`
              SET
                    `name`          = '{$params['name']}',
                    `tbl`           = '{$params['tbl']}',
                    `sen`           = '{$params['sen']}',
                    `description`   = '{$params['description']}',
                    `address`       = '{$params['address']}',
                    `placed`        = '{$params['placed']}',
                    `photo`         = '{$params['photo']}',

                    `obj_type`      = '{$params['obj_type']}',
                    `build_type`    = '{$params['build_type']}',
                    `db_type`       = '{$params['db_type']}',
                    `db_path`       = '{$params['db_path']}',
                    `db_descr`      = '{$params['db_descr']}',

                    `app`           = '{$params['app']}',
                    `os`            = '{$params['os']}',
                    `os_descr`      = '{$params['os_descr']}',
                    `remote`        = '{$params['remote']}',
                    `created`       = '{$params['created']}'

              WHERE id = {$params['id']}";


        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }


        $logIt = array(
            'id' => $params['id'],
            'new_value' => $params,
            'old_value' =>$oldvalue
        );

        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_DS, $logIt);

        $J->updated = $params['id'];
        $J->reLocate('apps.php');
        return $J;
    }



    public function selectDataSourceForm($preSelectedId=0) {
        $params = array('sources' =>getDatasources(), 'preSelectedId' => $preSelectedId);
        $params['sources'][0] = array ('id'=>0, 'tbl'=>'Выберите из списка');

        $this->printOut( includeFile(APP_PAGE_PARTS.'forms/form_select_ds.php', $params) );
    }

    public function editDsForm() {
        $params = array();
        $id = Arr::getValue($_REQUEST, 'id', false);
        if (!$id) $this->printOut( '<div class="control-group"><span class="label label-important"> Ошибка </span><span class="help-block alert alert-error">Некорректный запрос</span></div>' );

        $q = "SELECT * FROM `admin_conn_history` WHERE id = {$id}";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $this->printOut( '<div class="control-group"><span class="label label-important"> Ошибка </span><span class="help-block alert alert-error">Ошибка при работе с базой данных <!--('.DB::$mysqli->error.')--></span></div>' );
        }

        if (!($params = mysqli_fetch_array($res, MYSQLI_ASSOC))) {
            $this->printOut( '<div class="control-group"><span class="label label-important"> Ошибка </span><span class="help-block alert alert-error">Такого объекта в базе нет</span></div>' );
        }

        return $params;
    }



    public function dsList() {

        $params = array();
        $rows = array();

        if (!$this->error) {
            $now = time();

            $to_date = Arr::getValue($_POST, 'to_date', false);
            if ($to_date) $to_date = DateTime::createFromFormat('Y-m-d', $to_date);
            if ($to_date) $to_date = $to_date->getTimestamp();
            else $to_date = $now;

            $from_date = Arr::getValue($_POST, 'from_date', false);
            if ($from_date) $from_date = DateTime::createFromFormat('Y-m-d', $from_date);
            //if (!$from_date || $from_date >= $to_date) $from_date = $to_date - (60*60*24*30); // 30 дней
            if (!$from_date || $from_date->getTimestamp() >= $to_date) $from_date = DateTime::createFromFormat('Y-m-d', '2010-01-01');
            $from_date = $from_date->getTimestamp();



            $q = "  SELECT * FROM `admin_conn_history`
                    WHERE created >= FROM_UNIXTIME({$from_date})
                    AND   created <= FROM_UNIXTIME({$to_date})
                    ORDER BY created DESC";

            $res = DB::query($q);

            if (!$res || !DB::state()) $this->error = 'Ошибка при работе с базой данных';
            else {
                while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
                    $rows[] = $row;
                }
            }

        }

        $params['views'] = getAllViews_();
        $params['obj_types'] = getObjTypes();;
        $params['db_types'] = getClientDbTypes();
        $params['apps'] = getClientApps();
        $params['oss'] = getClientOSs();
        $params['btypes'] = getBuildTypes();


        $params['error'] = $this->error;
        $params['rows'] = $rows;
        $params['to_date'] = date('Y-m-d', $to_date);
        $params['from_date'] = date('Y-m-d', $from_date);

        $this->printOut(includeFile(APP_PAGE_PARTS.'list_ds.php', $params));
    }




    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }


}



/* ================================================================*/

    $page = new Page_install();
    Navbar::$expanded = 'lm-sys-install';

    // json requests
    if ($page->action == ACTIONS::INSTALL_NEWDS) echo $page->saveFormData();
    if ($page->action == ACTIONS::INSTALL_EDITDS) echo $page->updateFormData();

    // page requests
    if (!$page->action) {
        if (!Auth::isLogged()) reLocate(HTML_PATH);

        if (array_key_exists('download', $_REQUEST))  {
            Navbar::$active = 'download_dst';
            $page->selectDataSourceForm(Arr::getValue($_REQUEST, 'download', 0));
        }
        else if (array_key_exists(ACTIONS::INSTALL_EDITDS, $_REQUEST))  {
            $page->action = ACTIONS::INSTALL_EDITDS;
            $page->Form($page->editDsForm());
        }
        else if (array_key_exists('list_ds', $_REQUEST))  {
            Navbar::$expanded = 'lm-sys-bot';
            Navbar::$active = 'list_ds';
            $page->dsList();
        }
        else {
            $page->action = ACTIONS::INSTALL_NEWDS;
            Navbar::$active = 'create_ds';
            $page->Form();
        }
    }


?>